package com.oracle.controller;

import com.oracle.pojo.User;
import com.oracle.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/userReg",method = RequestMethod.POST)
    public String userReg(MultipartFile file, HttpSession session,String name, String password, Model model) throws IOException {
        /*String filename = file.getOriginalFilename();
        String ext = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID().toString()+ext;
        ServletContext servletContext = session.getServletContext();
        String uploadPath = servletContext.getRealPath("/statics/upload");
        File f = new File(uploadPath);
        if (!f.exists()){
            f.mkdir();
        }
        String finalPath = uploadPath + File.separator + filename;
        file.transferTo(new File(finalPath));*/
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        user.setRegTime(LocalDateTime.now());
        userService.addUser(user);
        return "redirect:/";
    }
    @RequestMapping(value = "/userLogin",method = RequestMethod.POST)
    public String userLogin(HttpSession session,String name, String password) {
        User user = userService.getUserByNameAndPwd(name, password);
        session.setAttribute("user",user);
        return "redirect:/";
    }
    @RequestMapping(value = "/to/existLogin",method = RequestMethod.GET)
    public String userLoginExist(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:/";
    }
}
